package ysutils

import (
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/text/gregex"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
	"math"
)

// GetExePath 获取执行程序的路径
func GetExePath() string {
	return gfile.SelfPath()
}

// FormatFileSize 字节的单位转换 保留两位小数
func FormatFileSize(fileSize int64) (size string) {
	if fileSize < 1024 {
		return fmt.Sprintf("%.2fB", float64(fileSize)/float64(1))
	} else if fileSize < (1024 * 1024) {
		return fmt.Sprintf("%.2fKB", float64(fileSize)/float64(1024))
	} else if fileSize < (1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fMB", float64(fileSize)/float64(1024*1024))
	} else if fileSize < (1024 * 1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fGB", float64(fileSize)/float64(1024*1024*1024))
	} else if fileSize < (1024 * 1024 * 1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fTB", float64(fileSize)/float64(1024*1024*1024*1024))
	} else { //if fileSize < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)
		return fmt.Sprintf("%.2fEB", float64(fileSize)/float64(1024*1024*1024*1024*1024))
	}
}

// FormatCommunicationRate 通讯速率换算
// 传入参数单位为 B/s
func FormatCommunicationRate(rate float64) (size string) {
	if rate < 1024 {
		return fmt.Sprintf("%.2fB/s", rate/float64(1))
	} else if rate < (1024 * 1024) {
		return fmt.Sprintf("%.2fKB/s", rate/float64(1024))
	} else if rate < (1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fMB/s", rate/float64(1024*1024))
	} else if rate < (1024 * 1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fGB/s", rate/float64(1024*1024*1024))
	} else if rate < (1024 * 1024 * 1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fTB/s", rate/float64(1024*1024*1024*1024))
	} else { //if rate < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)
		return fmt.Sprintf("%.2fEB/s", rate/float64(1024*1024*1024*1024*1024))
	}
}

func FindFile(paths string, pattern string) string {
	
	files := FindFiles(paths, pattern)
	if g.IsEmpty(files) {
		return ""
	}
	return files[0]
}

// FindAbsFile 找到绝对匹配的文件
// 找到的我呢间
func FindAbsFile(paths string, absPattern string) string {
	files := FindFiles(paths, "*"+absPattern)
	for _, file := range files {
		if gfile.Basename(file) == absPattern {
			return file
		}
	}
	return ""
}

// FindFiles 在指定的路径 <paths> 中搜索指定匹配方法，
// <paths> 可以用 , 号分隔。
func FindFiles(paths string, pattern string) []string {
	split := gstr.Split(paths, ",")
	out := make([]string, 0, 0)
	for _, s := range split {
		file, _ := gfile.ScanDirFile(s, pattern, true)
		out = append(out, file...)
	}
	if len(out) > 0 {
		return out
	}
	return nil
}

// FileNumToInt 计算文件开头数字值
func FileNumToInt(s string) int {
	
	match, err := gregex.MatchString("^[0-9]+", s) // 判断开头不是数字时直接返回最大值
	if g.IsEmpty(match) || err != nil {
		return math.MaxInt
	}
	out := gstr.TrimLeftStr(match[0], "0")
	return gconv.Int(out)
}
